import React, {useEffect, useState} from "react";
import {Spin, Tree} from "antd";
import {onTreeDrop} from "@/utils/utils";
import {DndNodeModel, TreeNodeModel} from "@/global";
import {TreeProps} from "antd/lib/tree";

/** 扩展Tree控件属性 */
export interface XtraTreeProps extends TreeProps {
  /** 是否展开第一个节点 */
  expandFirstNode?: boolean;
  /** 加载Tree数据 */
  onLoadTreeData: () => Promise<any>;
  /** 保存拖拽节点数据 */
  onSaveDndNodes?: (dnds: DndNodeModel[]) => Promise<any>;
}

/** 扩展Tree控件,支持拖拽 */
const XtraTree = function (props: XtraTreeProps) {
  const {expandFirstNode, onLoadTreeData, onSaveDndNodes, ...rest} = props;
  const [loading, setLoading] = useState<boolean>(true);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [data, setData] = useState<TreeNodeModel[]>([]);

  //加载数据
  useEffect(() => {
    onLoadTreeData().then(r => {
      setLoading(false);
      const tdata = r.data as TreeNodeModel[];
      setData(tdata);
      if (expandFirstNode && tdata && tdata.length > 0) {
        setExpandedKeys([tdata[0].key]);
      }
    });
  }, []);

  //如果需要展开第一个几点,并且未定义onExpand事件
  if (expandFirstNode && rest.onExpand === undefined) {
    rest.expandedKeys = expandedKeys;
    rest.onExpand = exkeys => {
      // @ts-ignore
      setExpandedKeys(exkeys);
    };
  }

  return (
    <Spin spinning={loading} delay={500}>
      <Tree
        {...rest}
        onDrop={(nodeInfo) => onTreeDrop(nodeInfo, data, setData, onSaveDndNodes)}
        treeData={data}
      />
    </Spin>
  );
};

/** 组件默认值 */
XtraTree.defaultProps = {
  expandFirstNode: false,
  blockNode: true,
  showIcon: true,
  draggable: true,
};
export default XtraTree;
